
import { PluginOption } from "vite";
import fs from 'fs';
import path from 'path';
import { IncomingMessage, ServerResponse } from "http";

/**
 * 开发接口 ‘/dev/icons’ 返回图标列表
 */
export default function (): PluginOption[] {
    return [{
        name: 'vite-menu-manage',
        apply: 'serve',
        configureServer: (server) => {
            // console.log('===>', d)
            server.middlewares.use('/dev/menu/add', (req: IncomingMessage, res: ServerResponse) => {
                try {
                    let body = '';
                    req.on('data', chunk => { body += chunk.toString() });
                    req.on('end', () => {
                        const filePath = path.join(__dirname, '../../public/config', 'menu.json');
                        fs.writeFileSync(filePath, body);
                        res.end();
                    });
                } catch (error: any) {
                    res.statusCode = 500;
                    res.end(`Error: ${error.message || '开发服务器错误'}`);
                }
            });
        }
    }]
}